// 创建路由对象,定义路由表
import vueRouter from 'vue-router'
// 路由组件懒加载
const Home = () => import('./pages/Home')
const About = () => import('./pages/About')
const News = () => import('./pages/News')
const Message = () => import('./pages/Message')
const Detail = () => import('./pages/Detail')
const router = new vueRouter({
  //   mode: 'history',
  routes: [
    {
      path: '/home',
      component: Home,
      children: [
        {
          path: 'news',
          component: News,
        },
        {
          path: 'message',
          component: Message,
          children: [
            {
              path: 'detail/:id?',
              component: Detail,
              name: 'de',
              props: function ($route) {
                return {
                  name: $route.query.name,
                  xxx: 1,
                }
              },
            },
          ],
        },
        // 让news成为home页面中默认展示的子路由
        {
          path: '/',
          redirect: 'news',
        },
      ],
    },
    {
      path: '/about',
      component: About,
    },
    {
      // 默认路由/时,默认展示home页面
      path: '/',
      redirect: '/home',
    },
  ],
})

// 需要登录才能访问的组件: About, Message和Detail
// const authPath = ['/about', '/home/message', '/home/message/detail']
const notAuthPath = ['/home', '/home/news'] // 只要判断当前浏览器地址栏的路径和这个数组中的字符串不相等,就可以进行权限管理了

// 定义全局前置路由守卫
router.beforeEach((to, from, next) => {
  // 获取目标路由的路径
  const path = to.path
  // 判断当前目标路径是否是需要权限管理的路径
  // 如果当前路径和不需要权限管理的路径都不相等,则return true.则说明当前路径需要权限管理
  const result = notAuthPath.every((item) => {
    return item !== path
  })
  if (result) {
    // 判断是否登录
    localStorage.getItem('token') ? next() : undefined
  } else {
    next()
  }
})

export default router
